def fout = new PrintWriter(new BufferedWriter(new FileWriter("yeastphenotypes.txt")))
def foutplain = new PrintWriter(new BufferedWriter(new FileWriter("yeastphenotypes-names.txt")))

def yeastfile = new File("phenotype_data.tab")
def yeastont = new File("ascomycete_phenotype.obo")
def yeastxp = new File("yeast_phenotype_xp.obo")

def term2id = [:]
def term = ""
def id = ""
yeastont.eachLine {line ->
  if (line.startsWith("id:")) {
    id = line.substring(3).trim()
  }
  if (line.startsWith("name:")) {
    term = line.substring(5).trim()
  }
  if (line.startsWith("[Term]")) {
    term2id[term] = id
  }
}

def map = [:]
def exp = new Expando()
exp.id = new String()
yeastxp.eachLine { line ->
  if (line.startsWith("id:")) {
    map[exp.id] = exp
    exp = new Expando()
    exp.id = line.substring(4).trim()
    exp.id = exp.id.substring(0, exp.id.indexOf("!")>-1?exp.id.indexOf("!"):exp.id.size()).trim()
  }
  if (line.startsWith("intersection_of: PATO")) {
    exp.quality = line.substring(line.indexOf("PATO"),line.indexOf("!")).trim()
  }
  if (line.startsWith("intersection_of: inheres_in")) {
    exp.e = line.substring(line.indexOf("inheres_in")+10, line.indexOf("!")>-1?line.indexOf("!"):line.size()).trim()
  }
  if (line.startsWith("intersection_of: towards")) {
    exp.t = line.substring(line.indexOf("towards")+7, line.indexOf("!")>-1?line.indexOf("!"):line.size()).trim()
  }
}
yeastfile.splitEachLine ("\t") { line ->
  def name = line[0]
  def p = line[9]
  if (term2id[p]!=null) {
    fout.println(line[3]+"\t"+term2id[p])
    foutplain.println(line[3]+"\t"+line[0])
  } else {
    def p1 = p.substring(0,p.indexOf(":")).trim()
    def p2 = p.substring(p.indexOf(":")+1).trim()
    def id1 = term2id[p1].trim()
    def id2 = term2id[p2].trim()
    def m1 = map[id1]
    def m2 = map[id2]
    if (m1?.id?.size()>0) {
      fout.println(line[3]+"\t"+term2id[p1]+"\t"+m1.quality+"\t"+m1.e+"\t"+m1.t+"\t"+term2id[p2]+"\t"+p2)
    } else {
      fout.println(line[3]+"\t"+term2id[p1]+"\t"+""+"\t"+""+"\t"+""+"\t"+term2id[p2]+"\t"+p2)
    }
    foutplain.println(line[3]+"\t"+line[0])
  }
}

fout.flush()
fout.close()
foutplain.flush()
foutplain.close()
